<template>
	<view class="main">
		<u-form :model="model" ref="uForm" label-width="150" label-position="top">
			<u-form-item label="封面图片">
				<u-upload width="160" height="160" :action="action" :form-data="formData"
					:beforeUpload="() => beforeUpload('post')"
					@on-success="(data, index) => onSuccess(data, index, 'post')"
					@on-remove="(index) => onRemove(index, 'post')">
				</u-upload>
			</u-form-item>
			<u-form-item label="联系方式">
				<u-input placeholder="请务必填写联系方式" v-show="model.contact.indexOf('http') === -1" v-model="model.contact"
					type="radio"></u-input>
				<u-upload class="link" :custom-btn="true" :action="action" :form-data="formData"
					:beforeUpload="() => beforeUpload('contact')"
					@on-success="(data, index) => onSuccess(data, index, 'contact')"
					@on-remove="(index) => onRemove(index, 'contact')" max-count="1">
					<template v-slot:addBtn>上传二维码图片</template>
				</u-upload>
			</u-form-item>
			<u-form-item label="解锁需要金币">
				<u-input placeholder="当用户解锁,你可以获得一半的解锁金币" v-model="model.unlock_cost" type="number"></u-input>
			</u-form-item>
			<u-form-item label="描述">
				<u-input placeholder="请输入内容" v-model="model.text" type="textarea"></u-input>
			</u-form-item>
			<u-form-item label="所在地区">
				<u-input type="select" v-model="model.city" placeholder="请选择地区" @click="selectIndexOpen"></u-input>
			</u-form-item>
		</u-form>
		<u-button class="btn" @click="submit">提交</u-button>
	</view>
</template>

<script>
	import {
		http,
		getCredentials
	} from '@/lib/js/request';
	import {
		goPage,
		delay
	} from '@/lib/js/utils';
	import {
		toast
	} from '@/lib/js/dailog';
	import moment from 'moment';
	import _ from 'lodash';
	export default {
		data() {
			return {
				model: {
					imgs: [],
					city: '',
					contact: ''
				},
				// 上传图片需要的两个参数
				action: '',
				formData: {}
			};
		},
		onShow() {
			this.model.city = uni.getStorageSync('city_new');
		},
		methods: {
			async submit() {
				await http('/post/new', this.model);
				toast('提交成功，请等待审核通过');
				await delay(1000);
				uni.navigateBack();
			},
			selectIndexOpen() {
				goPage(`/pages/index/indexed-list?redirect=new`);
			},
			async beforeUpload(type) {
				const {
					host,
					formData
				} = await getCredentials();
				this.action = host;
				this.formData = {
					...formData,
					key: type + '/' + moment().format('YYYYMMDD') + '/' + moment().format('HHmmss') + _.random(
						1000,
						9999) + '.jpg'
				};
			},
			onSuccess(data, index, type) {
				const url = this.action + this.formData.key
				if (type === 'post') this.$set(this.model.imgs, index, url);
				if (type === 'contact') this.model.contact = url
			},
			onRemove(index, type) {
				if (type === 'post') this.model.imgs.splice(index, 1);
				if (type === 'contact') this.model.contact = ''
			},

		}
	};
</script>

<style lang="scss" scoped>
	.main {
		padding: 40rpx;

		.link {
			color: $color-1;
		}

		.btn {
			margin-top: 50rpx;
		}
	}
</style>
